package controller

import (
	"fmt"
	"illuminant/model"
	"illuminant/service"
	"illuminant/util"

	jwt "github.com/appleboy/gin-jwt/v2"
	"github.com/gin-gonic/gin"
)

func ChangePasswd(c *gin.Context) {

	var (
		param struct {
			OldPasswd string `json:"old_passwd"`
			NewPasswd string `json:"new_passwd"`
		}
		err  error
		user *model.IlluminantUser
	)

	if err = c.BindJSON(&param); err != nil {
		util.Fail(c, util.REQUEST_PARAM_ERROR, err.Error(), nil)
		return
	}

	fmt.Printf("%v\n", param)

	claims := jwt.ExtractClaims(c)
	uid := claims["id"].(string)

	user, err = service.GetUserByID(uid)
	if err != nil {
		util.Fail(c, util.DATA_SEARCH_ERROR, err.Error(), nil)
		return
	}

	fmt.Printf("%v\n", user)
	if user.Password != param.OldPasswd {
		util.Fail(c, util.DATA_SEARCH_ERROR, "原密码错误", nil)
		return
	}

	_, err = service.UpdateUserPasswd(uid, param.NewPasswd)
	if err != nil {
		util.Fail(c, util.DATA_SEARCH_ERROR, err.Error(), nil)
		return
	}

	util.Success(c, "密码更新成功", nil)
}
